<?php
/**
 * Created by PhpStorm.
 * User: zeaven
 * Date: 14/12/19
 * Time: 15:00
 */

namespace Addons\CreditScript\Controller;

use Home\Controller\AddonsController;

class BaseController extends AddonsController {
    private $file_key = 'CreditScript_';
    private $fileData;

    function _initialize() {
        parent::_initialize();
        $vars = explode("\\", get_class($this));
        $this->file_key = $this->file_key. array_pop($vars);
        $this->fileData = F($this->file_key);
        if (empty($this->fileData)) {
            $this->fileData = array();
            foreach ($this->fields() as $field) {
                $this->fileData[$field['name']] = $field['value'];
            }
        }
    }

    function fields() {
        return array();
    }

    /**
     * 返回配置项的值
     * @param $key
     * @return mixed
     */
    function fieldValue($key) {
        $fields = $this->fileData;
        if (isset($fields[$key])) {
            return $fields[$key];
        } else {
            return null;
        }
    }

    function edit() {
        $fields = $this->fields();
        if (IS_POST) {
            $data = $this->fileStore();
            empty($data) && $data = array();
            foreach ($fields as &$field) {
                $value = I($field['name']);
                if (intval($field['is_must']) === 1 && empty($value)){
                    $this->error("参数[{$field['title']}]必填！");
                }
                $data[$field['name']] = $value;
            }
            $this->fileStore($data);
        } else {
            $data = $this->fileStore();
            foreach ($fields as &$value) {
                $data[$value['name']] && $value['value'] = $data[$value['name']];
            }
            return $fields;
        }
    }


    function del($id) {
        F($this->file_key, null);
    }

    /**
     * 读取保存数据
     * 读取: $this->fileStore('key')
     * 保存单个值: $this->fileStore('key','value');
     * 保存多个值: $this->fileStore(array('key1' => 'value1', 'key2' => 'value2');
     * @param string $key
     * @param string $value 为null时删除数据
     * @return null
     */
    private function fileStore($key = '', $value = '') {
        if ($key === '') {
            return $this->fileData;
        } else if ($value === '' && !is_array($key)) {
            return $this->fileData[$key];
        } else {
            if (is_null($value)) {
                unset($this->fileData[$key]);
            } else if (is_array($key)) {
                $this->fileData = array_merge($this->fileData, $key);
            } else {
                $this->fileData[$key] = $value;
            }
            F($this->file_key, $this->fileData);
            return null;
        }
    }
}